<template>
  <div class="app-container" :class="{ 'app-page': isAppPage, 'small': !isAppPage }" v-loading="loading">
    <div class="app-container-title">应用管理</div>
    <perfect-scrollbar class="app-box-body" :settings="{}">
      <template v-for="g in apps">
        <div class="app-box" v-if="isGroup(g)">
          <div class="app-box-head">
            <div class="app-box-title">{{ g.group_name }}</div>
            <div class="app-box-head-more" @click="handleShowCreateApp(g)">
              <i class="el-icon-plus"></i>APP
              <i class="el-icon-edit-outline app-edit-icon" @click.stop="handleShowUpdateGroup(g)"></i>
              <i class="el-icon-delete app-edit-icon" @click.stop="handleShowRemoveGroup(g)"></i>
            </div>
          </div>
          <draggable class="app-box-body" :list="g.subs" group="people" @change="log">
            <template v-for="app in g.subs">
              <div
                v-if="isApp(app)"
                class="app-info"
                :class="{ 'selected': selected?.group_id === app.group_id }"
                @click="handleSelect(app)"
              >
                <div class="app-icon" :style="$menuUtils.getIconStyle(app)">
                  <img
                    v-if="$menuUtils.getIconImg(app)"
                    :src="$menuUtils.getIconImg(app)"
                  />
                  <template v-else-if="$menuUtils.getIconFont(app)">
                    <i class="app-icon-white" :class="$menuUtils.getIconFont(app)"></i>
                    <i class="app-icon-color" :class="$menuUtils.getIconFont(app)"></i>
                  </template>
                </div>
                <div class="app-text">
                  <div class="app-name">{{ app.group_name }}</div>
                  <div class="edit">
                    <span class="btn" @click.stop="handleShowUpdateApp(app)"><i class="el-icon-edit"></i></span>
                    <span class="btn" @click.stop="handleShowRemoveApp(app)"><i class="el-icon-delete"></i></span>
                  </div>
                </div>
              </div>
            </template>
          </draggable>
        </div>
      </template>
    </perfect-scrollbar>

    <div class="actions">
      <el-button icon="el-icon-plus" class="app-group-add-btn" type="primary" plain @click="handleShowCreateGroup()">应用分组</el-button>
      <el-button v-if="!isAppPage" icon="fa fa-hand-point-up1" class="app-group-add-btn" type="primary" plain @click="showSelectConfirm()">确定选择</el-button>
      <el-button v-if="!isAppPage" class="app-group-add-btn" plain @click="handleClose()">取消</el-button>
    </div>

    <el-dialog
      :title="groupFormWinName"
      v-model="groupFormShow"
      :close-on-click-modal="false"
      :append-to-body="true">
      <form-group v-if="groupFormShow" :action-type="actionType" :current-data="currentGroup" :tty-custom="true" @success="handleGroupSuccess" @cancel="handleGroupCancel"></form-group>
    </el-dialog>
    <el-dialog
      :title="appFormWinName"
      v-model="appFormShow"
      :close-on-click-modal="false"
      :append-to-body="true">
      <form-app v-if="appFormShow" :action-type="actionType" :current-data="currentApp" :parent-group-id="parentGroupId" @success="handleAppSuccess" @cancel="handleAppCancel"></form-app>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue';
import { useRouter } from 'vue-router';
import _ from 'lodash';
import draggable from 'vuedraggable';
import formApp from '../basic/menus/form-app.vue';
import formGroup from '../basic/menus/form-group.vue';
import { $menuUtils } from "@jzl/utils";

const props = defineProps({
  tty: {
    type: Number,
    default: 1
  },
  isAppPage: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['selectApp', 'close']);

const router = useRouter();

const loading = ref(false);
const apps = ref([]);
const selected = ref(null);

const currentGroup = ref(null);
const groupFormShow = ref(false);
const groupFormWinName = ref('');
const appFormShow = ref(false);
const appFormWinName = ref('');
const parentGroupId = ref(-1);
const actionType = ref('edit');
const currentApp = ref(null);

const isGroup = (g) => {
  return g?.subs?.length > 0;
};

const isApp = (app) => {
  return app && !app.subs;
};

const getAppUserTypeLabel = (userType) => {
  let label = '共享平台用户';

  if (userType === 2) {
    label = '应用独立用户';
  } else if (userType === 3) {
    label = '共享+独立用户';
  }

  return label;
};

const init = async () => {
  loading.value = true;

  let ret = await api.admin.getAdminMenuTree(null, props.tty);
  let appsData = _.get(ret, 'groups', []);
  let notgroupsApps = [];
  let def = {
    group_name: '未分组',
    subs: []
  };

  _.each(appsData, app => {
    if (!app) return;

    if (isApp(app)) {
      notgroupsApps.push(app);
      app.forms = null;
      app.pagesH5 = null;
      app.pagesWeb = null;
      app.pagesDev = null;
    } else if (app.subs) {
      _.each(app.subs, as => {
        as.forms = null;
        as.pagesH5 = null;
        as.pagesWeb = null;
        as.pagesDev = null;
      });
    } else {
      app.subs = [];
    }
  });

  if (notgroupsApps && notgroupsApps.length) {
    def.subs = notgroupsApps;

    appsData.push(def);
  }

  apps.value = appsData;
  loading.value = false;
};

const handleSelect = (app, type) => {
  selected.value = app;

  let appCode = _.get(app, "group_code");
  if (type === 'mgr') {
    window.open(`/apps/jwsystem?app=${appCode}`);
  } else if (type === 'h5') {
    window.open(`/apps/jwh5?app=${appCode}`);
  } else if (type === 'web') {
    window.open(`/apps/jwpage?app=${appCode}`);
  } else if (props.isAppPage) {
    router.push({
      name: `portal-app`,
      params: {
        appId: _.get(app, "group_id")
      },
      replace: true
    });
  }
};

const showSelectConfirm = async () => {
  if (!selected.value) return;

  emit('selectApp', selected.value);

  // appDetailShow.value = true;
  // currentApp.value = selected.value;
  // appDetailWinTitle.value = `“${_.get(selected.value, 'group_name', '')}”应用下的资源`;
};

const handleShowCreateGroup = () => {
  actionType.value = 'createGroup';
  currentGroup.value = null;
  groupFormShow.value = true;
  groupFormWinName.value = '创建分组';
};

const handleShowUpdateGroup = (group) => {
  actionType.value = 'edit';
  groupFormShow.value = true;
  currentGroup.value = group;
  groupFormWinName.value = `修改分组: ${group.group_name}`;
};

const handleShowRemoveGroup = (group) => {
  let msg = `确定删除分组【${group.group_name}】?`;
  $jui.confirm(msg, '提示').then(async () => {
    let ret = await api.group.removeGroup(group.group_id);

    if (ret) {
      init();
    }
  });
};

const handleShowCreateApp = (g) => {
  actionType.value = 'createApp';
  currentApp.value = null;
  parentGroupId.value = _.get(g, 'group_id');
  appFormShow.value = true;
  groupFormWinName.value = `创建应用`;
};

const handleShowUpdateApp = (app) => {
  actionType.value = 'edit';
  appFormShow.value = true;
  currentApp.value = app;
  appFormWinName.value = `修改应用: ${app.group_name}`;
};

const handleShowRemoveApp = (app) => {
  let msg = `确定删除应用【${app.group_name}】?`;
  $jui.confirm(msg, '提示').then(async () => {
    let ret = await api.group.removeGroup(app.group_id);

    if (ret) {
      init();
    }
  });
};

const handleGroupSuccess = () => {
  groupFormShow.value = false;
  init();
};

const handleGroupCancel = () => {
  groupFormShow.value = false;
};

const handleAppSuccess = () => {
  appFormShow.value = false;
  init();
};

const handleAppCancel = () => {
  appFormShow.value = false;
};

const handleClose = () => {
  emit('close');
};

onMounted(() => {
  init();
});

watch(
  () => props.tty,
  () => {
    init();
  }
);
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-flow: column;
  height: 100%;
}
.app-container-title {
  font-size: 18px;
  text-align: center;
  display: inline-block;
  margin: auto;
  position: relative;
  padding: 0px 2px;

  &:after {
    content: " ";
    position: absolute;
    height: 10px;
    left: 0px;
    right: 0px;
    bottom: 0px;
    opacity: .5;
    background: #409EFF;
  }
}
.app-box-body {
  flex: 1;
  height: 100%;
}
.tty-icon {
  display: inline-flex;
  font-size: 10px;
  color: #409eff;
  width: 20px;
  height: 20px;
  align-items: center;
  justify-content: center;
  border-radius: 5px;

  &:hover {
    background: #FFF;
  }
}
.app-box {
  zoom: 1;
  font-size: 14px;
  padding: 0;
  font-family: Microsoft Yahei;

  .app-box-head {
    display: flex;
    align-items: center;
    position: relative;
    padding: 5px;
    zoom: 1;
    line-height: 1.1;

    .app-box-title {
      flex: 1;
      width: 100%;
      color: #666;
      display: flex;
      align-items: center;
    }

    .app-edit-icon {
      display: none;
      cursor: pointer;
    }

    .app-box-head-more {
      font-size: 14px;
      color: #409eff;
      cursor: pointer;
      display: none;

      > i {
        margin-left: 15px;
      }
    }

    &:hover {
      .app-edit-icon {
        display: inline-block;
        color: #409eff;
      }
    }
  }

  .app-box-body {
    padding: 5px;
    display: flex;
    flex-wrap: wrap;
    min-height: 70px;
  }
}

.app-info {
  width: 260px;
  padding: 10px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  cursor: pointer;
  border-radius: 5px;
  position: relative;
  overflow: hidden;
  transition: all .3s;
  margin-bottom: 10px;
  margin-right: 20px;
  background: #FFF;
  border: 1px solid #F1F1F1;

  .app-icon {
    width: 40px;
    height: 40px;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #666;
    margin-right: 10px;
    background: #F1F1F1;
    font-size: 24px;
    transition: all .3s;

    i {
      font-size: 24px;

      &.app-icon-white {
        color: #FFF;
      }
      &.app-icon-color {
        display: none;
      }
    }
  }
  .app-name {
    font-size: 15px;
    color: #222;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    line-height: 1.2;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .app-mark {
    font-size: 12px;
    color: #999;
    margin-top: 3px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }

  .edit {
    width: 36px;
    display: none;
    flex-flow: column;
    background: #FFF;
    position: absolute;
    right: 8px;
    border-radius: 5px;
    padding: 4px;
    font-size: 12px;
    text-align: center;

    .btn {
      padding: 2px;
    }
  }

  &:hover {
    background: #E9f1fF;
    border-color: #CCC;

    .app-icon {
      background: #FFF !important;

      i {
        &.app-icon-white {
          display: none;
        }
        &.app-icon-color {
          display: block;
        }
      }
    }

    .edit {
      display: flex;
    }
  }
}
.app-group-add-btn {
  border-radius: 2px;
  margin-top: 5px;
}

.app-container.small {
  margin: 0px;

  .app-box {
    margin-bottom: 5px;

    .app-box-head {
      padding: 10px 8px;
      .app-box-title {
        font-size: 16px;
      }
    }
    .app-box-body {
      min-height: 30px;
      padding: 0px;

      .app-info {
        width: 200px;
        margin-bottom: 5px;
        margin-right: 5px;
        padding: 8px;
        border: 1px solid #FFF;

        &:hover {
          background: #F1F1F1;
          border-color: #000;
        }
        &.selected {
          background: #F1F1F1;
          border-color: #000;
        }

        .app-icon {
          width: 30px;
          height: 30px;
          margin-right: 8px;

          i {
            font-size: 18px;
          }
        }
        .app-name {
        }
        .app-mark {
          display: none;
        }
      }
    }
  }
}
.app-page {
  padding: 20px;
  width: 100%;

  .app-container-title {
    display: none;
  }
  .app-box-head {
    &:hover {
      .app-box-head-more {
        display: inline-block;
      }
    }
  }
  .app-box-body {
    .app-box-title {
      width: auto;
      flex: none;
    }
    .app-box-head-more {
      font-size: 13px;
      margin-left: 15px;
    }

    .app-info {
      &:hover {
        .edit {
          display: flex;
        }
      }
    }
  }
}
</style>
